package zy.wq.security.bean;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;

public class AppSecurityUtils {

	public static User currentUser() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.getPrincipal() != null) {
			Object principal = auth.getPrincipal();
			if(principal instanceof User) {
				return (User)principal;
			}else {
				return new SimpleUser(null,auth.getName());
			}
		}
		return null;
	}
	
	public static void runAs(User user) {
		SecurityContextImpl sc = new SecurityContextImpl();
		sc.setAuthentication(new UsernamePasswordAuthenticationToken(user, "_dummy"));
		SecurityContextHolder.setContext(sc);
	}
	
	public static void clearSecurityContext() {
		SecurityContextHolder.setContext(null);
	}
}
